package com.spark.data

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.widget.ConfirmAlert
import com.spark.data.model.FileTransferNotifyModel
import com.spark.data.model.SaveFile2PersonalResModel
import kotlinx.android.synthetic.main.frag_file_transfer_notify.*

/**
 * 文件传输通知
 */
class FileTransferNotifyFragment : BaseFragment() {
    private var taskId = ""
    private var msgType = ""
    private lateinit var transferNotifyAdapter: FileTransferNotifyAdapter

    companion object {
        fun newInstance(taskId: String, msgType: String): FileTransferNotifyFragment {
            val target = FileTransferNotifyFragment()
            val args = Bundle()
            args.putString("taskId", taskId)
            args.putString("msgType", msgType)
            target.arguments = args
            return target
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_file_transfer_notify
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        arguments?.apply {
            taskId = getString("taskId")
            msgType = getString("msgType")
        }
        iv_back.setOnClickListener { pop() }

        transferNotifyAdapter = FileTransferNotifyAdapter(R.layout.item_borrow_material)
        recy_files.adapter = transferNotifyAdapter
        recy_files.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        transferNotifyAdapter.setOnItemChildClickListener { adapter, view, position ->
            val data = transferNotifyAdapter.data[position]
            if (data.personal)
                alert("该文件已在个人资料夹中")
            else
                save2Personal(data, position)
        }
        transferNotifyAdapter.addData(mutableListOf(
                FileTransferNotifyModel.ResultMap.File(filename = "安全生产标准化流程一览表"),
                FileTransferNotifyModel.ResultMap.File(filename = "安全生产标准化流程一览表"),
                FileTransferNotifyModel.ResultMap.File(filename = "安全生产标准化流程一览表"),
                FileTransferNotifyModel.ResultMap.File(filename = "安全生产标准化流程一览表"),
                FileTransferNotifyModel.ResultMap.File(filename = "安全生产标准化流程一览表")
        ))
    }

    private fun updateView(data: FileTransferNotifyModel) {
        data.resultMaps[0].apply {
            tv_sponsor.text = sendUserName.trim()
            tv_time.text = sdf().format(sendTime)
            tv_trans_message.text = description
            transferNotifyAdapter.addData(this.fileList)
        }


    }

    override fun onLazyInitView(savedInstanceState: Bundle?) {
        super.onLazyInitView(savedInstanceState)
        //fetchFileTransferResult()
    }

    @SuppressLint("CheckResult")
    private fun fetchFileTransferResult() {
        val params = mutableMapOf(
                Pair(Const.qr_taskId, taskId),
                Pair(Const.qr_messageType, msgType)
        )
        Http.request()
                .rxPost("${Const.base_url}${Const.act_file_transfer_notify_detail}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, FileTransferNotifyModel::class.java)?.apply {
                                if (code == "200") {
                                    updateView(this)
                                } else {
                                    error(msg)
                                }
                            }
                        },
                        {
                            hideLoader()
                            it.printStackTrace()
                            report(it)
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading()
                        }
                )
    }

    @SuppressLint("CheckResult")
    private fun save2Personal(file: FileTransferNotifyModel.ResultMap.File, position: Int) {
        val params = mutableMapOf(
                Pair(Const.qr_fileId, file.id.toString())
        )
        Http.request()
                .rxPost("${Const.base_url}${Const.act_save_file_2_personal}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, SaveFile2PersonalResModel::class.java)?.apply {
                                if (code == "200") {
                                    context?.apply { ConfirmAlert(this).show("已保存至个人文件夹") }
                                    file.personal = true
                                    transferNotifyAdapter.notifyItemChanged(position)
                                } else {
                                    error(msg)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            hideLoader()
                        },
                        {
                            hideLoader()
                        },
                        {
                            dispose = it
                            loading("保存中...")
                        }
                )
    }
}

/**
 * FIleTransferNotifyAdapter
 */
class FileTransferNotifyAdapter(layoutRes: Int) : BaseQuickAdapter<FileTransferNotifyModel.ResultMap.File, BaseViewHolder>(layoutRes) {
    override fun convert(helper: BaseViewHolder?, item: FileTransferNotifyModel.ResultMap.File?) {
        if (item == null) return
        helper?.apply {
            setText(R.id.tv_name, item.filename)
            getView<ImageView>(R.id.iv_save)?.apply {
                visibility = View.VISIBLE
                setImageResource(if (item.personal) R.drawable.ic_data_checked else R.drawable.ic_data_unchecked)
                setOnClickListener { onItemChildClickListener?.onItemChildClick(this@FileTransferNotifyAdapter, it, adapterPosition) }
            }
        }
    }


}